//
//  JKNewsDetailViewController.swift
//  ZhiHuDaily-Swift
//
//  Created by albert on 2018/3/7.
//  Copyright © 2018年 安永博. All rights reserved.
//

import UIKit
import WebKit
import MJRefresh

class JKNewsDetailViewController: JKBaseViewController {
    
    // MARK: - 公共属性
    
    /** 文章ID */
    var storyID: String?
    
    /** 记录是否是桌面3DTouch跳转过来的 */
    var is3DTouchJump: Bool = false
    
    /** 模型数组 首页有section的给这个赋值 */
    var stories: [[JKNewsListModel]]?
    
    /** 模型数组 其它主题没有section的给这个赋值 */
    var themeStories: [JKNewsListModel]?
    
    /** 索引 */
    var indexPath: IndexPath?
    
    /** 记录是否是点击了顶部topStory，如果是，返回时将不提示阅读位置 */
    var isTop: Bool = false
    
    /** 主页面vc */
    weak var storyListVc: (JKStoryListReadProtocol)?//(JKBaseViewController, JKStoryListReadProtocol)?
    
    /** 其它主题没有题图 使用主题背景图 */
    public var backgroundImageUrl: String?
    
    // MARK: - 私有属性
    
    private var model: JKNewsDetailModel?
    
    private var extraModel: JKNewsDetailExtraModel?
    
    private let TopScrollDistance:CGFloat = (54.0 + (JKIsIphoneX ? 24 : 0))
    
    /** 未请求到详情数据但是有分享的url，打开该url */
    private var request: URLRequest?
    
    /** 是否已经手动滑动过 */
    private var isDragged: Bool = false
    
    /** 下一条索引 */
    private var nextIndexPath: IndexPath?
    
    /** 上一条索引 */
    private var previousIndexPath: IndexPath?
    
    /** 顶部刷新控件 */
    private lazy var refreshHeaderView: UIView = {
        
        let refreshHeaderView = UIView()
        
        refreshHeaderView.backgroundColor = UIColor.clear
        refreshHeaderView.isHidden = true
        refreshHeaderView.frame = CGRect(x: 0, y: -self.scrollInsetTop - JKBarHeight, width: JKScreenW, height: JKBarHeight)
        webView.scrollView.addSubview(refreshHeaderView)
        
        refreshHeaderView.addSubview(refreshHeaderImageView)
        refreshHeaderView.addSubview(refreshHeaderLabel)
        
        return refreshHeaderView
    }()
    
    /** 顶部刷新控件中的图标 */
    private lazy var refreshHeaderImageView: UIImageView = {
        
        let arrowImgV = UIImageView()
        
        arrowImgV.image = UIImage(named: "ZHAnswerViewPrevIcon")
        
        return arrowImgV
    }()
    
    /** 顶部刷新控件中的label */
    private lazy var refreshHeaderLabel: UILabel = {
        
        let stateLabel = UILabel()
        
        //        stateLabel.backgroundColor = UIColor.clear
        stateLabel.textColor = JKSameRGBColor(218)
        stateLabel.font = UIFont.systemFont(ofSize: 13)
        
        return stateLabel
    }()
    
    /** 底部刷新控件 */
    private lazy var refreshFooterView: UIView = {
        
        let refreshFooterView = UIView()
        
        refreshFooterView.backgroundColor = UIColor.clear
        refreshFooterView.isHidden = true
        refreshFooterView.frame = CGRect(x: 0, y: JKScreenH, width: JKScreenW, height: JKBarHeight)
        webView.scrollView.addSubview(refreshFooterView)
        
        refreshFooterView.addSubview(refreshFooterImageView)
        refreshFooterView.addSubview(refreshFooterLabel)
        
        return refreshFooterView
    }()
    
    /** 底部刷新控件中的图标 */
    private lazy var refreshFooterImageView: UIImageView = {
        
        let arrowImgV = UIImageView()
        
        arrowImgV.image = UIImage(named: "ZHAnswerViewBackIcon")
        
        return arrowImgV
    }()
    
    /** 底部刷新控件中的label */
    private lazy var refreshFooterLabel: UILabel = {
        
        let stateLabel = UILabel()
        
//        stateLabel.backgroundColor = UIColor.clear
        stateLabel.textColor = JKSameRGBColor(218)
        stateLabel.font = UIFont.systemFont(ofSize: 13)
        
        return stateLabel
    }()
    
    /** 底部本文来自xxx合集view */
    private lazy var bottomContainerView: UIView = {
        
        // 添加bottomeView
        let bottomContainerView = UIView()
        bottomContainerView.backgroundColor = JKSameRGBColor(237)
        bottomContainerView.frame = CGRect(x: 20, y: 0, width: JKScreenW - 40, height: JKBarHeight)
        bottomContainerView.isHidden = true
        webView.scrollView.addSubview(bottomContainerView)
        
        bottomContainerView.addSubview(bottomContainerViewImgView)
        bottomContainerView.addSubview(bottomContainerViewLabel)
        
        // 当然这里也可以用手势，但是手势太多，可能会出问题吧。。
        let btn = UIButton(type: UIButtonType.custom)
        btn.frame = bottomContainerView.bounds
        bottomContainerView.addSubview(btn)
        btn.addTarget(self, action: #selector(tapbottomContainerView), for: UIControlEvents.touchUpInside)
        
        return bottomContainerView
    }()
    
    /** 底部本文来自xxx合集view上的imageView */
    private lazy var bottomContainerViewImgView: UIImageView = {
        
        // 左侧图片
        let imgView = UIImageView(frame: CGRect(x: 1, y: 1, width: JKBarHeight - 2, height: JKBarHeight - 2))
        
        return imgView
    }()
    
    /** 底部本文来自xxx合集view上的label */
    private lazy var bottomContainerViewLabel: UILabel = {
        
        // 右侧label
        let label = UILabel()
        label.frame = CGRect(x: JKBarHeight + 10, y: 10, width: JKScreenW - 40 - JKBarHeight - 10, height: JKBarHeight - 20)
//        label.backgroundColor =[UIColor.clear
        label.font = UIFont.systemFont(ofSize: 13)
        
        return label
    }()
    
    /** 正在加载 indicatorView */
    private lazy var indicatorView: UIActivityIndicatorView = {
        
        let indicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
        indicatorView.center = CGPoint(x: JKScreenW * 0.5, y: JKScreenH * 0.5)
        view.addSubview(indicatorView)
        
        return indicatorView
    }()
    
    /** 点赞后做动画的view */
    private lazy var zanAnimationView: JKNumberChangeAnimationView = {
        
        let zanAnimationView = JKNumberChangeAnimationView()
        
        zanAnimationView.frame = CGRect(x: (JKScreenW - 100) * 0.5, y: JKScreenH - JKBarHeight, width: 100, height: 26)
        zanAnimationView.isHidden = true
        view.addSubview(zanAnimationView)
        
        return zanAnimationView
    }()
    
    /** 夜间模式遮盖view */
    private lazy var coverView: UIView = {
        
        let coverView = UIView()
        
        coverView.backgroundColor = UIColor.black.withAlphaComponent(0.5)
        coverView.isUserInteractionEnabled = false
        coverView.isHidden = true
        view.addSubview(coverView)
        
        return coverView
    }()
    
    
    /** 点赞按钮 */
    @IBOutlet private weak var zanButton: UIButton!
    
    /** 点赞数label */
    @IBOutlet private weak var popularityLabel: UILabel!
    
    /** 评论数label */
    
    @IBOutlet private weak var commentCountLable: UILabel!
    
    /** 下一条新闻按钮 */
    @IBOutlet private weak var nextStoryButton: UIButton!
    
    /** topImageView的高度 */
    private let topImageHeight = JKScreenW * 0.85
    
    /** topImageView的Y值 -60 */
    private let topImageViewY: CGFloat = -60
    
    /** scrollView顶部内边距 */
    private let scrollInsetTop = JKScreenW * 0.85 - 120
    
    /** 当前状态栏样式 */
    private var currentStatusBarStyle: UIStatusBarStyle = UIStatusBarStyle.lightContent
    
    /** 底部的view */
    @IBOutlet private weak var bottomView: UIView!
    
    /** 底部的view高度约束 */
    @IBOutlet private weak var bottomViewHCons: NSLayoutConstraint!
    
    /** topStatusBarView */
    private lazy var topStatusBarView: UIView = {
        
        let topStatusBarView = UIView(frame: CGRect(x: 0, y: 0, width: JKScreenW, height: JKStatusBarHeight))
        topStatusBarView.isHidden = true
        topStatusBarView.backgroundColor = UIColor.white
        view.addSubview(topStatusBarView)
        
        return topStatusBarView
    }()
    
    /** 顶部的图片 */
    private lazy var topImageView: UIImageView = {
        
        let topImageView = UIImageView(frame: CGRect(x: 0, y: -scrollInsetTop + topImageViewY, width: JKScreenW, height: topImageHeight))
        
        let maskImageView = UIImageView(frame: topImageView.bounds)
        maskImageView.image = UIImage(named: "Home_Image_Mask_Plus")
        topImageView.addSubview(maskImageView)
        
        topImageView.isUserInteractionEnabled = true
        
        topImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(topImageClick)))
        
        return topImageView
    }()
    
    /** 文章标题label */
    private lazy var titleLabel: UILabel = {
        
        let titleLabel = UILabel()
        
        titleLabel.textColor = UIColor.white
        titleLabel.textAlignment = NSTextAlignment.left
        titleLabel.font = UIFont.boldSystemFont(ofSize: 19)
        titleLabel.numberOfLines = 0
        titleLabel.shadowColor = UIColor.darkGray
        titleLabel.shadowOffset = CGSize(width: 1, height: 0)
        titleLabel.lineBreakMode = NSLineBreakMode.byCharWrapping
        webView.scrollView.addSubview(titleLabel)
        
        titleLabel.translatesAutoresizingMaskIntoConstraints = false
        titleLabel.snp.makeConstraints({ (make) in
            make.width.equalTo(JKScreenW - 30)
            make.centerX.equalTo(self.contentView)
            make.bottom.equalTo(imageSourceLabel.snp.top).offset(-5)
        })
        
        return titleLabel
    }()
    
    /** 图片来源label */
    private lazy var imageSourceLabel: UILabel = {
        
        let imageSourceLabel = UILabel(frame: CGRect(x: 0, y: -20, width: JKScreenW - 15, height: 12))
        
        imageSourceLabel.textColor = UIColor.white
        imageSourceLabel.textAlignment = NSTextAlignment.right
        imageSourceLabel.font = UIFont.systemFont(ofSize: 9)
        webView.scrollView.addSubview(imageSourceLabel)
        
        return imageSourceLabel
    }()
    
    /** webView */
    private lazy var webView: WKWebView = {
        
        // 解决内存泄露问题
        let config = WKWebViewConfiguration()
        config.selectionGranularity = WKSelectionGranularity.character
        
        // 让网页内容自适应大小
        let jScript = "var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta); ('meta[name=description]').remove(); ('head').append( '<meta name=\"viewport\" content=\"width=device-width, initial-scale=1,user-scalable=no\">' );"
        let wkUScript = WKUserScript(source: jScript, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: false)
        
        let wkUController = WKUserContentController()
        wkUController.addUserScript(wkUScript)
        //        [wkUController addScriptMessageHandler:self name:@"openInfo"]
        config.userContentController = wkUController
        
        // 创建WKWebView
        let webView = WKWebView(frame: JKScreenBounds, configuration: config)
//        webView.isOpaque = false
        webView.scrollView.jk_adapt_iOS_11_scrollView()
        webView.scrollView.contentInset = UIEdgeInsets(top: scrollInsetTop, left: 0, bottom: 0, right: 0)
        webView.backgroundColor = UIColor.white
        webView.scrollView.backgroundColor = UIColor.clear
        webView.navigationDelegate = self
        webView.scrollView.delegate = self
//        if ([webView respondsToSelector:@selector(setAllowsLinkPreview:)]) {
//            webView.allowsLinkPreview = YES
//        }
        
        webView.scrollView.mj_footer = MJRefreshBackFooter(refreshingTarget: nil, refreshingAction: nil)
        
        contentView.insertSubview(webView, at: 0)
        
        webView.translatesAutoresizingMaskIntoConstraints = false
        webView.snp.makeConstraints({ (make) in
            make.top.equalTo(contentView)
            make.left.right.equalTo(0)
            make.bottom.equalTo(self.bottomView.snp.top)
        })
        
        webView.scrollView.insertSubview(topImageView, at: 0)
        
        let whiteView = UIView(frame: CGRect(x: 0, y: 0, width: JKScreenW, height: -topImageViewY))
        whiteView.backgroundColor = JKGlobalBgColor
        webView.scrollView.insertSubview(whiteView, at: 1)
        
        return webView
    }()
    
    
    
    // MARK:- 生命周期方法
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        navigationController?.setNavigationBarHidden(true, animated: true)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        UIApplication.shared.setStatusBarStyle(currentStatusBarStyle, animated: true)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        UIApplication.shared.setStatusBarStyle(UIStatusBarStyle.lightContent, animated: true)
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        
        
    }

    // MARK: - 初始化
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.white
        
        coverView.frame = CGRectMake(0, 0, JKScreenW, JKScreenH - self.bottomViewHCons.constant)
        
        if is3DTouchJump {
            
            nextStoryButton.isEnabled = false
            
            return
        }
        
        calculateNextIndexPath()
        
        calculatePreviousIndexPath()
        
        setupHeaderFooter()
    }
    
    override func setup() {
        
        indicatorView.startAnimating()
        
        navBgView.isHidden = true
        
        bottomViewHCons.constant = JKCurrentHomeIndicatorHeight + 44
        
        let swipe = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(swipe(gesture:)))
        swipe.edges = UIRectEdge.right
        webView.addGestureRecognizer(swipe)
        
        NotificationCenter.default.addObserver(self, selector: #selector(updateSkin), name: NSNotification.Name(rawValue: JKSkinModelDidChangedNotification), object: nil)
        
        if (!JKSQLiteManager.queryIsLikedWithStoryID(storyID: self.storyID)) { return }
        self.zanButton.isSelected = true
        self.popularityLabel.textColor = self.commentCountLable.backgroundColor
    }
    
    /** 计算下一篇文字索引 */
    private func calculateNextIndexPath() {
        
        if indexPath == nil {
            return
        }
        
        nextStoryButton.isEnabled = true
        
        var nextIndexPath: IndexPath? = nil
        
        if stories != nil {
            
            let sectionArr = self.stories![self.indexPath!.section]
            
            if (self.indexPath!.row < sectionArr.count - 1) {
                
                nextIndexPath = IndexPath(row: self.indexPath!.row + 1, section: self.indexPath!.section)
                
            }else if (self.indexPath!.section < self.stories!.count - 1) {
                
                nextIndexPath = IndexPath(row: 0, section: self.indexPath!.section + 1)
                
            }else{
                
                self.nextStoryButton.isEnabled = false
            }
            
        }else if (self.themeStories != nil) {
            
            if (self.indexPath!.row < self.themeStories!.count - 1) {
                
                nextIndexPath = IndexPath(row: self.indexPath!.row + 1, section: 0)
                
            }else{
                
                self.nextStoryButton.isEnabled = false
            }
        }
        
        self.nextIndexPath = nextIndexPath
    }
    
    /** 计算上一篇文字索引 */
    private func calculatePreviousIndexPath() {
        
        if indexPath == nil {
            return
        }
        
        var previousIndexPath: IndexPath? = nil
        
        if (self.stories != nil) {
            
            if (self.indexPath!.row > 0) {
                
                previousIndexPath = IndexPath(row: self.indexPath!.row - 1, section: self.indexPath!.section)
                
            }else if (self.indexPath!.section > 0) {
                
                let sectionArr = self.stories![self.indexPath!.section - 1]
                
                previousIndexPath = IndexPath(row: sectionArr.count - 1, section: self.indexPath!.section - 1)
                
            }else{
                
                previousIndexPath = nil
            }
            
        }else if (self.themeStories != nil) {
            
            if (self.indexPath!.row > 0) {
                
                previousIndexPath = IndexPath(row: self.indexPath!.row - 1, section: 0)
                
            }else{
                
                previousIndexPath = nil
            }
        }
        
        self.previousIndexPath = previousIndexPath
    }
    
    /** swipe */
    @objc private func swipe(gesture: UISwipeGestureRecognizer) {
        
        if gesture.state == UIGestureRecognizerState.began {
            
            commentClick()
        }
    }
    
    /** 设置HeaderFooter */
    private func setupHeaderFooter() {
        
        if is3DTouchJump { return }
        
        // header
        refreshHeaderImageView.frame = (previousIndexPath == nil) ?
            CGRect.zero :
            CGRect(x: refreshHeaderView.width * 0.5 - 47, y: 12, width: 15, height: 20)
        
        refreshHeaderLabel.frame = (previousIndexPath == nil) ?
            CGRect(x: 0, y: 0, width: refreshHeaderView.width, height: refreshHeaderView.height) :
            CGRect(x: refreshHeaderView.width * 0.5 - 24, y: 0, width: 200, height: refreshHeaderView.height)
        
        refreshHeaderLabel.textAlignment = (previousIndexPath == nil) ? NSTextAlignment.center : NSTextAlignment.left
        refreshHeaderLabel.text = (previousIndexPath == nil) ? "已经是第一篇了" : "载入上一篇"
        
        // footer
        refreshFooterImageView.frame = (nextIndexPath == nil) ?
            CGRect.zero :
            CGRect(x: self.refreshFooterView.width * 0.5 - 47, y: 12, width: 15, height: 20)
        
        refreshFooterLabel.frame = (nextIndexPath == nil) ?
            CGRect(x: 0, y: 0, width: refreshFooterView.width, height: refreshFooterView.height) :
            CGRect(x: refreshFooterView.width * 0.5 - 24, y: 0, width: 200, height: refreshFooterView.height)
        
        refreshFooterLabel.textAlignment = (nextIndexPath == nil) ? NSTextAlignment.center : NSTextAlignment.left
        refreshFooterLabel.text = (nextIndexPath == nil) ? "已经是最后一篇了" : "载入下一篇"
        
    }
    
    // MARK: - 加载数据
    
    override func loadNewData() {
        
        if storyID == nil {
            
            indicatorView.stopAnimating()
            
            return
        }
        
        JKNewsListGetDataModel.loadDetailDataWithID(ID: storyID!, detailBlock: { (detailModel, json, error) in
            
            self.indicatorView.stopAnimating()
            
            if error != nil {
                
                return
            }
            
            self.model = detailModel
            self.loadDetailView(model: detailModel!)
            
        }) { (extraModel, error) in
            
            if error != nil {
                return
            }
            
            self.extraModel = extraModel
            
            self.commentCountLable.text = extraModel?.comments
            var popularity = extraModel?.popularity
            
            let popCount = Int(popularity ?? "0") ?? 0
            
            popularity = JKSQLiteManager.queryIsLikedWithStoryID(storyID: self.storyID) ? "\(popCount + 1)" : popularity
            
            self.popularityLabel.text = popularity
        }
    }
    
    /** 加载详情 */
    private func loadDetailView(model: JKNewsDetailModel) {
        
        var body = model.body
        
        if body != nil {
            
            var tmpStr = ""
            
            for c in model.css! {
                
                JKSQLiteManager.cacheStoryDetailCss(ID: model.id, cssUrlStr: c)
                
                let cssPath = (JKCssDirectory as NSString).appendingPathComponent(model.id! + ".css")
                
                let isCached = FileManager.default.fileExists(atPath: cssPath)
                
                if (isCached) {
                    
                    if let cssStr = try? String(contentsOfFile: cssPath) {
                        
                        tmpStr = String(format: "<style> %@ </style>", cssStr)
                        
                    }else{
                        
                        tmpStr = String(format: "<link href='%@' rel='stylesheet' type='text/css' />%@", c, tmpStr)
                    }
                    
                }else{
                    
                    tmpStr = String(format: "<link href='%@' rel='stylesheet' type='text/css' />%@", c, tmpStr)
                }
                
                // 由于它的CSS中已经写死了 顶部图片的高度就是200,可以自己来改
                body = String(format: "%@ <style> .headline .img-place-holder { height: 0px } </style> %@", tmpStr, body!)
                // .content-wrap {background: #3CB371}
                
                webView.loadHTMLString(body!, baseURL: nil)
            }
            
        }else{
            
            request = URLRequest(url: URL(string: model.share_url ?? "about:blank")!)
            
            webView.load(request!)
        }
        
        if model.section != nil {
            
            bottomContainerView.isHidden = true
            
            self.bottomContainerViewImgView.jk_setImage(withUrlStr: model.section!.thumbnail, placeHolder: "Setting_Avatar")
            
            self.bottomContainerViewLabel.text = String(format: "本文来自:  %@ · 合集", model.section!.name ?? "")
        }
        
        titleLabel.text = model.title

        if (model.image_source != nil) {
            
            self.imageSourceLabel.text = String(format: "图片:  %@", model.image_source!)
        }

        if (model.image != nil) {
            
            topImageView.jk_setImage(withUrlStr: model.image!, placeHolder: "Image_Preview")
            
            return
        }

        if (model.images == nil || model.images?.count == 0) {
            
            topImageView.jk_setImage(withUrlStr: backgroundImageUrl, placeHolder: "Image_Preview")
            
            return
        }
        
        topImageView.jk_setImage(withUrlStr: model.images![0], placeHolder: "Image_Preview")
    }

    // MARK: - 点击事件
    
    /** 收藏文章 */
    private func collectStory() {
        
        if self.model == nil {
            return
        }
        
        if JKSQLiteManager.queryIsCollectedWithStoryID(storyID: self.model!.id) {
            
            JKProgressHUD.showInfo(withStatus: "您已收藏该文章！")
            
            return
        }
        
        if JKSQLiteManager.updateCollectedStatusWithStoryID(storyID: self.model!.id, collected: true) {
            
            JKProgressHUD.showSuccess(withStatus: "收藏成功！")
            
            return
        }

        JKProgressHUD.showError(withStatus: "收藏失败！")
    }
    
    // 点击详情底部合集view
    @objc private func tapbottomContainerView() {
        
        
        let sectionVc = JKSectionStoryListViewController()
        sectionVc.section = self.model?.section
        navigationController?.pushViewController(sectionVc, animated: true)
    }
    
    @IBAction func backButtonClick(_ sender: Any) {
        
        navigationController?.popViewController(animated: true)
    }
    
    /** 上一条或下一条 */
    private func changeStory(indexPath: IndexPath?, isNext: Bool) {
        
        if indexPath == nil { return }
        
        let vc = JKNewsDetailViewController()
        vc.storyListVc = self.storyListVc
        
        var listModel: JKNewsListModel? = nil
        
        if (self.stories != nil) {
            
            vc.stories = self.stories
            listModel = self.stories![indexPath!.section][indexPath!.row]
            
        }else if (self.themeStories != nil) {
            
            vc.themeStories = self.themeStories
            listModel = self.themeStories![indexPath!.row]
        }
        
        vc.storyID = listModel?.id
        vc.indexPath = indexPath
        vc.backgroundImageUrl = backgroundImageUrl
        
        UIView.beginAnimations(nil, context: nil)
        UIView.setAnimationCurve(UIViewAnimationCurve.easeInOut)
        UIView.setAnimationDuration(0.75)
        
        navigationController?.pushViewController(vc, animated: false)
        
        UIView.setAnimationTransition(isNext ? .curlUp : .curlDown, for: (navigationController?.view)!, cache: false)
        
        UIView.commitAnimations()
        
        view.removeFromSuperview()
        removeFromParentViewController()
    }
    
    /** 上一条 */
    private func previousStory() {
        
        changeStory(indexPath: previousIndexPath, isNext: false)
    }
    
    /** 下一条 */
    @IBAction private func nextStoryButtonClick() {
        
        changeStory(indexPath: nextIndexPath, isNext: true)
    }
    
    /** 分享 */
    @IBAction private func shareButtonClick(_ sender: Any) {
        
        JKShareView.showWithModel(model: self.model)
    }
    
    /** 点击顶部图片 */
    @objc private func topImageClick() {
        
        if topImageView.image == nil {
            return
        }
        
        JKImageBrowserView.showWith(image: topImageView.image)
    }
    
    /** 点赞 */
    @IBAction private func zanButtonClick(_ sender: UIButton) {
        
        var originalNum: Int = 0
        
        if self.extraModel != nil {
            
            originalNum = Int(self.extraModel!.popularity ?? "0") ?? 0
        }
        
        sender.isSelected = !sender.isSelected
        
        if sender.isSelected {
            
            UIView.animate(withDuration: 0.2, animations: {
                
                sender.transform = CGAffineTransformMakeScale(1.5, 1.5)
                
            }, completion: { (_) in
                
                UIView.animate(withDuration: 0.2, animations: {
                    
                    sender.transform = CGAffineTransform.identity
                    
                }, completion: { (_) in
                    
                })
            })
        }
        
        JKSQLiteManager.updateIsLikedWithStoryID(storyID: self.storyID, isLiked: sender.isSelected)
        
        if !sender.isSelected {
            
            self.popularityLabel.textColor = UIColor.lightGray
            self.popularityLabel.text = self.extraModel?.popularity ?? "0"
            
            return
        }
        
        self.zanAnimationView.isHidden = false
        self.zanAnimationView.originalNumber = originalNum
        
        self.popularityLabel.text = "\(originalNum + 1)"
        self.popularityLabel.textColor = JKColor(29, 171, 239)
        
        self.zanAnimationView.beginAnimationWithTransform(transform: CGAffineTransformMakeTranslation(0, -self.zanAnimationView.height * 1.5 - JKCurrentHomeIndicatorHeight), complete: nil)
    }
    
    /** 查看评论 */
    @IBAction private func commentClick() {
        
        let vc = JKCommentViewController()
        
        vc.storyID = storyID
        vc.extraModel = extraModel
        
        navigationController?.pushViewController(vc, animated: true)
    }
    
    deinit {
        
        webView.scrollView.delegate = nil
        
        if indexPath == nil || isTop { return }
        
        NotificationCenter.default.post(name: NSNotification.Name(JKLastReadIndexNotification), object: nil, userInfo: [JKLastReadIndexKey : indexPath!])
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

// MARK: - webView代理

extension JKNewsDetailViewController: WKNavigationDelegate {
    
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        
        if  model == nil {
            return
        }
        
        // 更新文章为已读状态
        JKSQLiteManager.updateReadStatusWithStoryID(storyID: model!.id)
    
        storyListVc?.reloadReadStoryWith(indexPath: indexPath)
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        
        self.request = nil
//        webView.scrollView.scrollEnabled = YES
        
        indicatorView.stopAnimating()
        
        self.topStatusBarView.isHidden = !(webView.scrollView.contentOffset.y >= 0)

        if (self.model?.section != nil) {
            
            webView.scrollView.contentInset = UIEdgeInsetsMake(self.scrollInsetTop, 0, JKBarHeight + 30, 0)
        }

        // 获取网页中图片url
        getImageUrlsViaJs()
        
        // 禁止捏合手势
        let javascript = "var meta = document.createElement('meta');meta.setAttribute('name', 'viewport');meta.setAttribute('content', 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no');document.getElementsByTagName('head')[0].appendChild(meta);"
        webView.evaluateJavaScript(javascript, completionHandler: nil)
    }
    
    // 这里是js，主要目的实现对url的获取
    private func getImageUrlsViaJs() {
        
        webView.evaluateJavaScript("function registerImageClickAction() { var imgs=document.getElementsByTagName('img'); var length = imgs.length; for (var i = 0; i < length; i++) { img = imgs[i]; img.onclick = function() { window.location.href = 'image-preview:'+this.src }}}", completionHandler: nil)
        webView.evaluateJavaScript("registerImageClickAction();", completionHandler: nil)
    }
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        
        guard let url = navigationAction.request.url else {
            
            decisionHandler(WKNavigationActionPolicy.allow)
            
            return
        }
        
        if url.scheme == "image-preview" {
            
            let path = url.absoluteString.substring(from: "image-preview:".count).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
            
            JKImageBrowserView.showWith(imageUrlStr: path)
            
            decisionHandler(WKNavigationActionPolicy.cancel)
            
        }else if url.scheme == "http" || url.scheme == "https" {
            
            if request != nil ||
                url.absoluteString.contains("daily_mp4") ||
                url.absoluteString.contains("v.qq.com") ||
                url.absoluteString.contains("video.qq.com") {
                
                decisionHandler(WKNavigationActionPolicy.allow)
                
            }else{
                
                let browser = JKBrowserViewController()
                browser.request = navigationAction.request
                navigationController?.pushViewController(browser, animated: true)
                
                decisionHandler(WKNavigationActionPolicy.cancel)
            }
            
        }else{
            
            decisionHandler(WKNavigationActionPolicy.allow)
        }
        
        
//        NSURL *url = navigationAction.request.URL
//        //预览图片
//        if ([url.scheme isEqualToString:@"image-preview"]) {
//            NSString* path = [url.absoluteString substringFromIndex:[@"image-preview:" length]]
//
//            //path 就是被点击图片的url
//            //path = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
//            path = [path stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]
//            [JKImageBrowserView showWithImageUrlStr:path]
//
//            decisionHandler(WKNavigationActionPolicyCancel)
//
//        }else if ([url.scheme isEqual:@"http"] || [url.scheme isEqual:@"mailto"] || [url.scheme isEqual:@"https"]) {
//
//            if (self.request || [url.absoluteString containsString:@"daily_mp4"] || [url.absoluteString containsString:@"v.qq.com"] || [url.absoluteString containsString:@"video.qq.com"]) {
//                decisionHandler(WKNavigationActionPolicyAllow)
//
//            }else{
//                JKBrowserViewController *browserVc = [[JKBrowserViewController alloc] init]
//                browserVc.request = navigationAction.request
//                [self.navigationController pushViewController:browserVc animated:YES]
//                decisionHandler(WKNavigationActionPolicyCancel)
//            }
//
//        }else{
//            decisionHandler(WKNavigationActionPolicyAllow)
//        }
    }
}

// MARK: - scrollView 代理

extension JKNewsDetailViewController {
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        topStatusBarView.isHidden = !(scrollView.contentOffset.y >= 0)
        
        UIView.animate(withDuration: 0.25) {
            
            self.refreshFooterImageView.transform = (self.webView.scrollView.mj_footer.state == MJRefreshState.pulling) ? CGAffineTransform(rotationAngle: CGFloat.pi-0.001) : CGAffineTransform.identity
        }
        
        if (scrollView.contentOffset.y < -self.scrollInsetTop) {
            
            self.webView.scrollView.scrollIndicatorInsets = UIEdgeInsetsMake(-scrollView.contentOffset.y - (JKIsIphoneX ? JKStatusBarHeight : 0), 0, 0, 0)
            
        }else {
            
            self.webView.scrollView.scrollIndicatorInsets = UIEdgeInsetsMake(self.scrollInsetTop - (JKIsIphoneX ? JKStatusBarHeight : 0), 0, 0, 0)
        }
        
        if (scrollView.contentOffset.y > JKScreenH) { return }
        
        UIView.animate(withDuration: 0.25) {
            
            self.refreshHeaderImageView.transform = ((-self.scrollInsetTop - scrollView.contentOffset.y) / self.TopScrollDistance >= 1) ? CGAffineTransform(rotationAngle: CGFloat.pi+0.001) : CGAffineTransform.identity
        }
        self.refreshHeaderView.isHidden = false
        self.refreshHeaderView.y = (-self.scrollInsetTop - JKBarHeight) + (scrollView.contentOffset.y + self.scrollInsetTop) * 0.2
        
        self.topImageView.y = -self.scrollInsetTop + topImageViewY + (scrollView.contentOffset.y + self.scrollInsetTop) * 0.5
        
        scrollView.contentOffset = (scrollView.contentOffset.y <= -self.topImageHeight) ? CGPoint(x: 0, y: -self.topImageHeight) : CGPoint(x: 0, y: scrollView.contentOffset.y)
        
        if (currentSkinModel == JKNightSkinModelValue) { return }
        
        let style = (scrollView.contentOffset.y >= 0) ? UIStatusBarStyle.default : UIStatusBarStyle.lightContent
        UIApplication.shared.setStatusBarStyle(style, animated: true)

        currentStatusBarStyle = style
    }
    
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {

        return nil
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        
        if (self.model?.section != nil) {
            
            self.refreshFooterView.isHidden = false
            
            // 添加详情底部合集view
            self.bottomContainerView.y = self.webView.scrollView.mj_footer.frame.origin.y
            self.refreshFooterView.y = self.bottomContainerView.y + 30 + JKBarHeight
            self.bottomContainerView.isHidden = false
            
        }else{
            
            self.refreshFooterView.y = self.webView.scrollView.mj_footer.y
            self.refreshFooterView.isHidden = false
        }
    }
    
    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        
        if is3DTouchJump { return }
        
        if ((-self.scrollInsetTop - scrollView.contentOffset.y) / TopScrollDistance >= 1) {
            
            previousStory()
        }
        
        if ((self.webView.scrollView.mj_footer.state == MJRefreshState.pulling)) {
            
            if (!self.nextStoryButton.isEnabled) { return }
            
            nextStoryButtonClick()
        }
    }
}

// MARK: - 3DTouch

@available(iOS 9.0, *)
extension JKNewsDetailViewController {
    
    override var previewActionItems: [UIPreviewActionItem] {
        
        let action1 = UIPreviewAction(title: "收藏", style: .default) { (action, previewViewController) in
            self.collectStory()
        }
        
        let action3 = UIPreviewAction(title: "取消", style: .destructive) { (action, previewViewController) in
            print("我是取消按钮")
        }
//        ////该按钮可以是一个组，点击该组时，跳到组里面的按钮。
//        let subAction1 = UIPreviewAction(title: "测试1", style: .selected) { (action, previewViewController) in
//            print("我是测试按钮1")
//        }
//        let subAction2 = UIPreviewAction(title: "测试2", style: .selected) { (action, previewViewController) in
//            print("我是测试按钮2")
//        }
//        let subAction3 = UIPreviewAction(title: "测试3", style: .selected) { (action, previewViewController) in
//            print("我是测试按钮3")
//        }
//        let groupAction = UIPreviewActionGroup(title: "更多", style: .default, actions: [subAction1, subAction2, subAction3])
        
        return [action1, action3]
    }
}

extension JKNewsDetailViewController{
    
    @objc override func updateSkin() {
        
        if vcSkinModel == currentSkinModel {
            return
        }
        
        super.updateSkin()
        
        if (currentSkinModel == JKNightSkinModelValue) { // 夜间模式
            
            self.topStatusBarView.backgroundColor = JKNightSkinNavColor
            self.bottomView.backgroundColor = JKNightSkinBgColor
            self.bottomContainerView.backgroundColor = JKNightSkinBgColor.withAlphaComponent(0.6)
            
            self.bottomContainerViewLabel.textColor = UIColor.white
            self.coverView.isHidden = false
            
            UIApplication.shared.setStatusBarStyle(.lightContent, animated: true)
            currentStatusBarStyle = UIStatusBarStyle.lightContent
            
        }else{ // 日间模式
            
            self.topStatusBarView.backgroundColor = UIColor.white
            self.bottomView.backgroundColor = JKColor(237, 237, 237)
            self.bottomContainerView.backgroundColor = JKColor(237, 237, 237)
            
            self.bottomContainerViewLabel.textColor = UIColor.black
            self.coverView.isHidden = true
            
            currentStatusBarStyle = (self.webView.scrollView.contentOffset.y >= 0) ? UIStatusBarStyle.default : UIStatusBarStyle.lightContent
            UIApplication.shared.setStatusBarStyle(currentStatusBarStyle, animated: true)
        }
    }
}
